import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/providers/auth_provider.dart';
import '../../../core/providers/curriculum_provider.dart';
import '../../../core/api/api_service.dart';
import '../../../core/providers/user_extra_info_provider.dart';
import '../../../core/api/api_client.dart';

class ProfileSetupPage extends ConsumerStatefulWidget {
  const ProfileSetupPage({super.key});

  @override
  ConsumerState<ProfileSetupPage> createState() => _ProfileSetupPageState();
}

class _ProfileSetupPageState extends ConsumerState<ProfileSetupPage> {
  int _currentStep = 0;
  String? _selectedStage;
  String? _selectedGrade;
  String? _selectedSemester; // 新增：上册/下册选择
  final List<String> _selectedSubjects = [];
  String _learningGoal = '';
  bool _isSaving = false;
  final ApiService _apiService = ApiService();

  final List<String> _stages = ['小学', '初中', '高中'];
  final Map<String, List<String>> _grades = {
    '小学': ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级'],
    '初中': ['初一', '初二', '初三'],
    '高中': ['高一', '高二', '高三'],
  };

  // 根据学段显示不同的科目
  final Map<String, List<String>> _subjectsByStage = {
    '小学': ['语文', '数学', '英语'],
    '初中': ['语文', '数学', '英语', '物理', '化学', '生物'],
    '高中': ['语文', '数学', '英语', '物理', '化学', '生物', '历史', '地理', '政治'],
  };

  final List<String> _goals = ['提高基础成绩', '查漏补缺', '冲刺高分', '保持稳定'];
  final List<String> _semesters = ['上册', '下册']; // 新增：上册/下册选项

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('完善学习档案'),
        automaticallyImplyLeading: false,
      ),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            _buildProgressIndicator(),
            _buildStepTip(),
            Expanded(
              child: IndexedStack(
                index: _currentStep,
                children: <Widget>[
                  _buildStageSelection(),
                  _buildGradeSelection(),
                  _buildSemesterSelection(), // 新增：上册/下册选择
                  _buildSubjectSelection(),
                  _buildGoalSelection(),
                ],
              ),
            ),
            _buildNavigationButtons(),
          ],
        ),
      ),
    );
  }

  Widget _buildStepTip() {
    final ColorScheme cs = Theme.of(context).colorScheme;
    String tip;
    switch (_currentStep) {
      case 0:
        tip = '请选择你当前的学段（小学/初中/高中）';
        break;
      case 1:
        tip = '选择你所在的年级，后续可以在资料中修改';
        break;
      case 2:
        tip = '选择当前学习的上册或下册';
        break;
      case 3:
        tip = '选择你想要练习的科目（可多选），可随时调整';
        break;
      case 4:
        tip = '选择一个学习目标，帮助我为你规划路径';
        break;
      default:
        tip = '';
    }

    if (tip.isEmpty) return const SizedBox.shrink();

    return Container(
      width: double.infinity,
      margin: const EdgeInsets.fromLTRB(16, 8, 16, 0),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: cs.primaryContainer,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: <Widget>[
          Icon(Icons.info_outline, color: cs.primary),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              tip,
              style: TextStyle(color: cs.onPrimaryContainer.withOpacity(0.9)),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProgressIndicator() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: List.generate(5, (index) {
          // 更新为5个步骤
          final isActive = index <= _currentStep;
          return Expanded(
            child: Container(
              height: 4,
              margin: const EdgeInsets.symmetric(horizontal: 2),
              decoration: BoxDecoration(
                color:
                    isActive
                        ? Theme.of(context).colorScheme.primary
                        : Theme.of(
                          context,
                        ).colorScheme.onSurface.withOpacity(0.2),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
          );
        }),
      ),
    );
  }

  Widget _buildStageSelection() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            '选择学段',
            style: Theme.of(
              context,
            ).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          Text(
            '请选择你当前的学段',
            style: TextStyle(
              color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
            ),
          ),
          const SizedBox(height: 24),
          ...(_stages.map(
            (stage) => _buildSelectionCard(
              title: stage,
              isSelected: _selectedStage == stage,
              onTap: () {
                setState(() {
                  _selectedStage = stage;
                  _selectedGrade = null; // 重置年级选择
                  _selectedSemester = null; // 重置学期选择
                  _selectedSubjects.clear(); // 重置科目选择
                });
              },
            ),
          )),
        ],
      ),
    );
  }

  Widget _buildGradeSelection() {
    if (_selectedStage == null) return const SizedBox.shrink();

    final grades = _grades[_selectedStage!] ?? [];

    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            '选择年级',
            style: Theme.of(
              context,
            ).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          Text(
            '请选择你当前的年级',
            style: TextStyle(
              color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
            ),
          ),
          const SizedBox(height: 24),
          ...(grades.map(
            (grade) => _buildSelectionCard(
              title: grade,
              isSelected: _selectedGrade == grade,
              onTap: () {
                setState(() {
                  _selectedGrade = grade;
                });
              },
            ),
          )),
        ],
      ),
    );
  }

  Widget _buildSemesterSelection() {
    if (_selectedGrade == null) return const SizedBox.shrink();

    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            '选择学期',
            style: Theme.of(
              context,
            ).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          Text(
            '请选择当前学习的上册或下册',
            style: TextStyle(
              color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
            ),
          ),
          const SizedBox(height: 24),
          ...(_semesters.map(
            (semester) => _buildSelectionCard(
              title: semester,
              isSelected: _selectedSemester == semester,
              onTap: () {
                setState(() {
                  _selectedSemester = semester;
                });
              },
            ),
          )),
        ],
      ),
    );
  }

  Widget _buildSubjectSelection() {
    if (_selectedStage == null || _selectedSemester == null)
      return const SizedBox.shrink();

    final subjects = _subjectsByStage[_selectedStage!] ?? [];

    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            '选择科目',
            style: Theme.of(
              context,
            ).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          Text(
            '请选择你想要练习的科目（可多选）',
            style: TextStyle(
              color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
            ),
          ),
          const SizedBox(height: 24),
          Wrap(
            spacing: 10,
            runSpacing: 10,
            children:
                subjects.map((subject) {
                  final isSelected = _selectedSubjects.contains(subject);
                  return GestureDetector(
                    onTap: () {
                      setState(() {
                        if (isSelected) {
                          _selectedSubjects.remove(subject);
                        } else {
                          _selectedSubjects.add(subject);
                        }
                      });
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 14,
                        vertical: 10,
                      ),
                      decoration: BoxDecoration(
                        color:
                            isSelected
                                ? Theme.of(context).colorScheme.primaryContainer
                                : Theme.of(
                                  context,
                                ).colorScheme.surfaceContainerHighest,
                        borderRadius: BorderRadius.circular(16),
                        border:
                            isSelected
                                ? Border.all(
                                  color: Theme.of(context).colorScheme.primary,
                                )
                                : null,
                      ),
                      child: Text(
                        subject,
                        style: TextStyle(
                          color:
                              isSelected
                                  ? Theme.of(context).colorScheme.primary
                                  : Theme.of(context).colorScheme.onSurface,
                          fontWeight:
                              isSelected ? FontWeight.w600 : FontWeight.w500,
                        ),
                      ),
                    ),
                  );
                }).toList(),
          ),
        ],
      ),
    );
  }

  Widget _buildGoalSelection() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            '学习目标',
            style: Theme.of(
              context,
            ).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          Text(
            '请选择你的学习目标',
            style: TextStyle(
              color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
            ),
          ),
          const SizedBox(height: 24),
          ...(_goals.map(
            (goal) => _buildSelectionCard(
              title: goal,
              isSelected: _learningGoal == goal,
              onTap: () {
                setState(() {
                  _learningGoal = goal;
                });
              },
            ),
          )),
        ],
      ),
    );
  }

  Widget _buildSelectionCard({
    required String title,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: double.infinity,
        margin: const EdgeInsets.only(bottom: 10),
        padding: const EdgeInsets.all(14),
        decoration: BoxDecoration(
          color:
              isSelected
                  ? Theme.of(context).colorScheme.primaryContainer
                  : Theme.of(context).colorScheme.surfaceContainerHighest,
          borderRadius: BorderRadius.circular(12),
          border:
              isSelected
                  ? Border.all(color: Theme.of(context).colorScheme.primary)
                  : null,
        ),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text(
                title,
                style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
                  color:
                      isSelected
                          ? Theme.of(context).colorScheme.primary
                          : Theme.of(context).colorScheme.onSurface,
                ),
              ),
            ),
            if (isSelected)
              Icon(
                Icons.check_circle,
                color: Theme.of(context).colorScheme.primary,
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildNavigationButtons() {
    return Container(
      padding: const EdgeInsets.all(20),
      child: SafeArea(
        child: Row(
          children: <Widget>[
            if (_currentStep > 0)
              Expanded(
                child: OutlinedButton.icon(
                  onPressed: () {
                    setState(() {
                      _currentStep--;
                    });
                  },
                  icon: const Icon(Icons.arrow_back),
                  label: const Text('上一步'),
                ),
              ),
            if (_currentStep > 0) const SizedBox(width: 12),
            Expanded(
              child: FilledButton.icon(
                onPressed: (_canProceed() && !_isSaving) ? _handleNext : null,
                icon: Icon(
                  _currentStep == 4
                      ? (_isSaving ? Icons.hourglass_bottom : Icons.check)
                      : Icons.arrow_forward,
                ),
                label: Text(_currentStep == 4 ? '完成' : '下一步'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  bool _canProceed() {
    switch (_currentStep) {
      case 0:
        return _selectedStage != null;
      case 1:
        return _selectedGrade != null;
      case 2:
        return _selectedSemester != null;
      case 3:
        return _selectedSubjects.isNotEmpty;
      case 4:
        return _learningGoal.isNotEmpty;
      default:
        return false;
    }
  }

  // 检查是否所有必要信息都已填写
  bool _isProfileComplete() {
    return _selectedStage != null &&
        _selectedGrade != null &&
        _selectedSemester != null &&
        _selectedSubjects.isNotEmpty &&
        _learningGoal.isNotEmpty;
  }

  void _handleNext() async {
    if (_currentStep < 4) {
      setState(() {
        _currentStep++;
      });
    } else {
      // 最终检查：确保所有信息都已填写
      if (!_isProfileComplete()) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('请完成所有必要信息的填写')));
        return;
      }

      try {
        setState(() => _isSaving = true);
        // 保存用户画像并更新认证状态
        await _saveProfile();
        await ref.read(authProvider.notifier).completeProfileSetup();
        if (!mounted) return;
        context.go('/dashboard');
      } catch (e) {
        if (!mounted) return;
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('保存失败：$e')));
      } finally {
        if (mounted) setState(() => _isSaving = false);
      }
    }
  }

  Future<void> _saveProfile() async {
    try {
      print('🔄 开始保存用户额外信息...');

      // 检查token状态
      ApiClient().checkTokenStatus();

      // 从认证状态获取token并重新设置（确保token是最新的）
      final authState = ref.read(authProvider);
      if (authState.accessToken != null) {
        print('🔄 重新设置认证Token...');
        ApiClient().setAuthToken(authState.accessToken!);
        ApiClient().checkTokenStatus();
      } else {
        print('❌ 认证状态中没有Token');
      }

      // 最终验证：确保所有必要数据都已填写
      if (!_isProfileComplete()) {
        throw Exception('用户必须完成所有选择才能保存');
      }

      // 构建请求数据（所有参数都是用户必须选择的）
      final requestData = {
        'schoolStage': _selectedStage!,
        'grade': _selectedGrade!,
        'volume': _selectedSemester!,
        'subjects': _selectedSubjects.join('/'),
        'goals': _learningGoal,
      };

      print('📤 请求数据: $requestData');
      print('📋 用户选择详情:');
      print('   学段: $_selectedStage');
      print('   年级: $_selectedGrade');
      print('   学期: $_selectedSemester');
      print('   科目: ${_selectedSubjects.join(', ')}');
      print('   目标: $_learningGoal');

      // 调用API保存用户额外信息
      final response = await _apiService.saveUserExtraInfo(requestData);

      print('✅ 保存成功');
      print('📊 响应状态码: ${response.statusCode}');
      print('📄 响应数据: ${response.data}');

      // 检查响应状态
      if (response.statusCode == 200) {
        final responseData = response.data;
        if (responseData['code'] == 200) {
          print('🎉 用户额外信息保存成功！');

          // 更新本地状态
          final userExtraInfoNotifier = ref.read(
            userExtraInfoProvider.notifier,
          );
          await userExtraInfoNotifier.updateUserExtraInfo(
            UserExtraInfo(
              grade: _selectedGrade,
              volume: _selectedSemester,
              subjects: _selectedSubjects.join('/'),
              goals: _learningGoal,
            ),
          );

          // 获取教材大纲
          await _loadCurriculumData();
        } else {
          print('❌ 保存失败: ${responseData['msg']}');
          throw Exception('保存失败: ${responseData['msg']}');
        }
      } else {
        print('❌ 保存失败，状态码: ${response.statusCode}');
        throw Exception('保存失败: ${response.statusCode}');
      }
    } catch (e) {
      print('💥 保存用户额外信息异常: $e');
      rethrow;
    }
  }

  // 获取教材大纲数据
  Future<void> _loadCurriculumData() async {
    try {
      print('📚 开始获取教材大纲...');

      if (_selectedSubjects.isNotEmpty) {
        // 使用用户的第一个科目和年级信息
        final subject = _selectedSubjects.first;
        final grade = '$_selectedGrade$_selectedSemester';

        print('📚 获取教材大纲: subject=$subject, grade=$grade');

        await ref
            .read(curriculumProvider.notifier)
            .loadCurriculumBySubjectAndGrade(subject: subject, grade: grade);

        print('✅ 教材大纲获取成功');
      } else {
        print('⚠️ 没有选择科目，跳过教材大纲获取');
      }
    } catch (e) {
      print('❌ 获取教材大纲失败: $e');
      // 不抛出异常，因为这不是关键步骤
    }
  }
}
